// market相关业务逻辑
import { Next } from '../app'
import { IGroupMessageEvent } from '../../interface/bot.interface'
import { format, splitLine, wrapCommandFn } from '../../utils'
import { Shard } from '../../interface/screeps.interface'
import ErrorType from '../../constants/errorType'
import { getMarketOrderInfo, getRoomObject } from '../../request/screeps'

/**
 * 查看市场订单信息
 */
export const lookOrder = wrapCommandFn(
    async (e: IGroupMessageEvent, next: Next) => {
        try {
            const shard = e.args[1] as Shard
            const res = await getMarketOrderInfo(e.args[0], shard)
            if (res.data.ok) {
                const orderList = res.data.list
                const type = e.args[2] === 'sell' ? 'sell' : 'buy'
                const orders = orderList.filter((order) => order.type === type).sort((a, b) => b.price - a.price)
                const end = Math.min(orders.length, 8)
                const strs = [`${e.args[1]} ${e.args[0]}前${end}的${type}订单：`]
                const requests = []
                for (let i = 0; i < end; i++) {
                    requests.push(getRoomObject(orders[i].roomName as string, shard))
                }
                const roomRes = await Promise.all(requests)
                for (let i = 0; i < end; i++) {
                    const order = orders[i]
                    const data = roomRes[i].data
                    const user = Object.values(data.users).find((item) => item.badge)
                    strs.push(
                        `[${user?.username}/${order.roomName}]:\n ${order.price.toFixed(3)}/${order.amount}/${
                            order.remainingAmount
                        }`,
                    )
                }
                e.group.sendMsg(splitLine(strs))
            }
            next()
        } catch (error) {
            e.group.sendMsg(ErrorType.REQUEST_ERROR)
        }
    },
    () => {
        return format(
            '/order [resourceType] [shard] [type]',
            ['resourceType: 资源名', 'shard: 分片', 'type: buy/sell'],
            '查看市场订单信息',
        )
    },
)
